package com.example.blue;

import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static CrashHandler instance = new CrashHandler();
    private Thread.UncaughtExceptionHandler defaultHandler;
    private Context context; // ✅ 定义在类里，全局变量

    private CrashHandler() {}

    public static CrashHandler getInstance() {
        return instance;
    }

    public void init(Context ctx) {
        this.context = ctx.getApplicationContext();
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        // 保存日志
        Log.e("CrashHandler", "捕获异常", e);

        // 这里就是捕获到的所有未处理异常
        handleException(e);

        // 不直接退出程序，可以延迟退出或重启
        try {
            Thread.sleep(2000); // 停留2秒，方便显示提示或保存日志
        } catch (InterruptedException eq) {
            eq.printStackTrace();
        }

        // 可选：重启应用
//        Intent intent = new Intent(context, MainActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(intent);

        // 结束当前进程
//        android.os.Process.killProcess(android.os.Process.myPid());
//        System.exit(1);

        // 如果不处理，交给系统默认处理
//        if (defaultHandler != null) {
//            defaultHandler.uncaughtException(t, e);
//        }
    }

    private void handleException(Throwable ex) {
        if (ex == null) return;

        // 1️⃣ 保存日志到文件
        saveCrashLog(ex);

        // 2️⃣ 可显示一个Toast或Dialog提示用户
        new Thread(() -> {
            Looper.prepare();
            Toast.makeText(context, "程序出现异常", Toast.LENGTH_SHORT).show();
            Looper.loop();
        }).start();
    }
    private void saveCrashLog(Throwable ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        String crashInfo = sw.toString();

        File logFile = new File(context.getExternalFilesDir(null), "crash_log.txt");
        try (FileWriter writer = new FileWriter(logFile, true)) {
            writer.write("---- " + new Date() + " ----\n");
            writer.write(crashInfo + "\n\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

